package com.example.c94s3plyhyfc.web;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class TimestampConverter implements Converter<String, Timestamp> {

    @Override
    public Timestamp convert(String s) {
        String fmt = "yyyy-MM-dd";
        if (s.matches("\\d{4}/\\d{2}/\\d{2}")) {
            fmt = "yyyy/MM/dd";
        } else if (s.matches("\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2}")) {
            fmt = "yyyy/MM/dd HH:mm:ss";
        }
        Date date = null;
        try {
            date = new SimpleDateFormat(fmt).parse(s);
            return new Timestamp(date.getTime());
        } catch (ParseException e) {
            return null;
        }
    }
}
